package com.xzy.learn.spring.ioc.overview.dependency.lookup;

import com.xzy.learn.spring.annotation.VIP;
import com.xzy.learn.spring.entity.User;
import com.xzy.learn.spring.ioc.overview.config.DependencyLookupDemoBeanConfig;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Map;

/**
 * 依赖查找
 *
 * @author xzy.xiao
 * @date 2022/5/28  9:45
 */
public class DependencyLookupDemo {
    public static void main(String[] args) {
        BeanFactory beanFactory = new AnnotationConfigApplicationContext(DependencyLookupDemoBeanConfig.class);

//        lookupByNameInRealTime(beanFactory);
//        lookupByNameInLazy(beanFactory);
//        lookupByType(beanFactory);
//        lookupCollectionByType(beanFactory);
        lookupByAnnotation(beanFactory);
    }

    /**
     * 根据名称 & 实时查找
     *
     * @param beanFactory -
     */
    private static void lookupByNameInRealTime(BeanFactory beanFactory) {
        User bean = beanFactory.getBean("user", User.class);
        System.out.println("实时查找：" + bean);
    }

    /**
     * 根据名称 & 延迟查找
     *
     * @param beanFactory -
     */
    private static void lookupByNameInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("userObjectFactory");
        User object = objectFactory.getObject();
        System.out.println("延时查找：" + object);
    }

    /**
     * 根据类型 & 单个Bean
     *
     * @param beanFactory -
     */
    private static void lookupByType(BeanFactory beanFactory) {
        User bean = beanFactory.getBean(User.class);
        System.out.println(bean);
    }

    /**
     * 根据类型 & 多个bean
     *
     * @param beanFactory -
     */
    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            beansOfType.forEach((id, bean) -> {
                System.out.println(id + "  ->  " + bean);
            });
        }
    }

    /**
     * 根据注解
     *
     * @param beanFactory -
     */
    private static void lookupByAnnotation(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Object> beansWithAnnotation = listableBeanFactory.getBeansWithAnnotation(VIP.class);
            beansWithAnnotation.forEach((id, bean) -> {
                System.out.println(id + "  ->  " + bean);
            });
        }
    }
}
